<template>
  <div class="app-container">
    <div class="bgWhite radius8 pt20 flex col-top row-between">
      <el-form class="pl20 pr20" :model="queryParams" ref="queryForm" :inline="true" label-width="100px" v-show="showSearch">
        <div>
          <el-form-item label="手机号" prop="phoneNumber">
            <el-input
                v-model="queryParams.phoneNumber"
                placeholder="搜索手机号"
                class="resetInput"
                style="width: 200px"
                :suffix-icon="Search"
                clearable
            />
          </el-form-item>
          <el-form-item label="商机来源" prop="opportunitySource">
            <el-select class="head-container"
                       v-model="queryParams.opportunitySource"
                       placeholder="商机来源"
                       size="large" style="width: 200px"
                       clearable>
              <el-option
                  v-for="dict in bus_source"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="分配状态" prop="distributionStatus">
            <el-select
                v-model="queryParams.distributionStatus"
                placeholder="分配状态"
                size="large" style="width: 200px"
                clearable>
              <el-option
                  v-for="dict in bus_customer_allocation"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
            </el-select>
          </el-form-item>         
        </div>
      </el-form>
	  <div class="pr20 flex col-center">
	    <el-button class="searchBtn" type="defaultBtn" @click="handleQuery">搜索</el-button>
	    <el-button class="searchBtn" icon="Refresh" @click="resetQuery">重置</el-button>
	  </div>
    </div>
    <div class="bgWhite radius8 p20 mt25">
      <div class="flex col-center row-between mb20">
        <span class="fb fs16">商机列表</span>
        <div>
          <el-button type="defaultBtn" @click="handleAdd" v-hasPermi="['opportunity:add']">添加商机</el-button>
          <el-button type="operate" @click="handleImport" v-hasPermi="['opportunity:importData']">批量导入</el-button>
          <el-button type="operate" :disabled="multiple" @click="allocationFormSub" v-hasPermi="['opportunity:publicAllocation']">分配商机</el-button>
        </div>
      </div>
      <el-table v-loading="loading"
	   :data="opportunityList" 
	   :header-row-style="{background:'#FAFAFA',color:'#0C1019',height:'54px'}"
	   :cell-style="{height:'54px'}"
	  @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="客户名称" align="center" prop="customerName"/>
        <el-table-column label="商机来源" align="center" prop="opportunitySource">
          <template #default="scope">
            <dict-tag :options="bus_source" :value="scope.row.opportunitySource"/>
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" prop="phoneNumber"/>
        <el-table-column label="归属部门" align="center" prop="departName"/>
        <el-table-column label="归属小组" align="center" prop="teamName"/>
        <el-table-column label="归属业务经理" align="center" prop="businessManagerName"/>
        <el-table-column label="分配状态" align="center">
          <template #default="scope">
			  <div class="flex col-center row-center"
			  :class="activeStatus(scope.row.distributionStatus)"
			  >
			  	<span class="drop"></span>
			  	<dict-tag :options="bus_customer_allocation" :value="scope.row.distributionStatus"/>
			  </div>
          </template>
        </el-table-column>

        <el-table-column label="添加时间" align="center" prop="createTime" width="160px" :show-overflow-tooltip="true"/>

        <el-table-column  fixed="right" label="操作" align="center" width="300px" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link class="linkBtnColor" type="primary"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['opportunity:edit']" >编辑</el-button>
            <el-button link class="linkBtnColor" type="primary"
                @click="allocationFormSub(scope.row)"
                v-hasPermi="['opportunity:publicAllocation']">分配商机</el-button>
            <el-button link class="linkBtnColor" type="primary"
                @click="detailsOpenFun(scope.row)"
                v-hasPermi="['opportunity:getDetails']">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </div>

    <!-- 添加或修改商机对话框 -->
    <el-dialog :title="title" center v-model="open" :rules="rules" width="710px" append-to-body>
      <el-form ref="refForm" class="pt20" :model="form" :rules="rules" label-width="85px" :inline="true">
		<el-form-item label="商机来源" prop="opportunitySource">
		  <el-select
			  size="large"
			  v-model="form.opportunitySource"
			  placeholder="请选择来源渠道"
			  clearable
			  class="my-label">
			<el-option
				v-for="dict in bus_source"
				:key="dict.value"
				:label="dict.label"
				:value="dict.value"/>
		  </el-select>
		</el-form-item>
		<el-form-item label="客户姓名" prop="customerName" style="margin-right: 0;margin-left: 18px;">
		  <el-input size="large" v-model="form.customerName" class="my-label" placeholder="请输入客户姓名"/>
		</el-form-item>
		<el-form-item label="手机号码" prop="phoneNumber">
		  <el-input size="large" v-model="form.phoneNumber" class="my-label" placeholder="请输入手机号码"/>
		</el-form-item>
		<el-form-item label="客户地址" prop="customerAddress" style="margin-right: 0;margin-left: 18px;">
		  <el-cascader
			  size="large"
			  ref="cascader"
			  style="width:220px;"
			  v-model="form.address"
			  :props="address"
			  @change="handleChangeAddress"
			  clearable
		  >
		  </el-cascader>
		</el-form-item>
		<el-form-item label="客户作物">
		  <el-select v-model="form.cropIds" size="large" class="my-label" multiple placeholder="请选择客户作物">
			<el-option
				v-for="item in cropVarietyList"
				:key="item.id"
				:label="item.cropName"
				:value="item.id"
			></el-option>
		  </el-select>
		</el-form-item>
		<el-form-item label="商机渠道" prop="opportunityChannel" style="margin-right: 0;margin-left: 18px;">
		  <el-select
			  size="large"
			  v-model="form.opportunityChannel"
			  placeholder="请选择商机渠道"
			  clearable
			  class="my-label" @change="busChannelOnclike">
			<el-option
				v-for="dict in bus_channel"
				:key="dict.value"
				:label="dict.label"
				:value="dict.value"/>
		  </el-select>
		</el-form-item>
		<el-form-item label="选择部门" prop="deptId">
		  <el-select
		      size="large"
			  v-model="form.deptId"
			  placeholder="请选择部门"
			  clearable
			  class="my-label">
			<el-option
				v-for="dict in deptListOptions"
				:key="dict.deptId"
				:label="dict.deptName"
				:value="dict.deptId"/>
		  </el-select>
		</el-form-item>
            <el-form-item label="客户尊称" prop="customerTitle" style="margin-right: 0;margin-left: 18px;">
              <el-select
			      size="large"
                  v-model="form.customerTitle"
                  placeholder="选择客户尊称"
                  clearable
                  class="my-label">
                <el-option
                    v-for="dict in honorific"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"/>
              </el-select>
            </el-form-item>
          
		    <el-form-item label="微信账号" prop="wxAccount">
		      <el-input size="large" v-model="form.wxAccount" class="my-label" placeholder="请输入微信账号"/>
		    </el-form-item>
		
       
            <el-form-item label="客户生日"  prop="birthday" style="margin-right: 0;margin-left: 18px;">
              <el-date-picker size="large" clearable 
			  style="width: 220px;"
			  v-model="form.birthday"
			  type="date"
			  placeholder="请选择客户生日">
              </el-date-picker>
            </el-form-item>
          
		    <el-form-item label="客户需求" prop="customerNeed">
		      <el-input size="large" v-model="form.customerNeed" class="my-label" placeholder="请输入客户需求"/>
		    </el-form-item>
		 
			<div>
				<div class="">
					<div class="flex col-top fs14" style="position: relative;">
						<div class="tagItem" style="margin-right: 15px;">
							客户标靶
						</div>
						<div style="width: 515px;" :class="{'minHeight':height1 == false}">
							<span class="disInBlock mr20 cursor cate-item"
							:class="[{'main-color':dict.disabled == true},{'color2':dict.disabled == false}]"
							v-for="(dict,index) in bus_target" :key="index"
							@click="tabItem(index,1)"
							>
								{{dict.label}}
							</span>	
						</div>
						<span class="main-color absolute cursor" style="position: absolute;right: 8px;top: 8px;"
						@click="height1 = !height1"
						>{{height1 == false ? '展开' : '收起'}}</span>
					</div>
				</div>
				<div class="mb15">
					<div class="flex col-top fs14" style="position: relative;">
						<div class="tagItem" style="margin-right: 15px;">
							其他标签
						</div>
						<div style="width: 515px;" :class="{'minHeight':height2 == false}">
							<span class="disInBlock mr20 cursor cate-item"
							:class="[{'main-color':dict.disabled == true},{'color2':dict.disabled == false}]"
							v-for="(dict,i) in bus_other_tag" :key="i"
							@click="tabItem(i,2)"
							>
								{{dict.label}}
							</span>	
						</div>
						<span class="main-color absolute cursor" style="position: absolute;right: 8px;top: 8px;"
						@click="height2 = !height2"
						>{{height2 == false ? '展开' : '收起'}}</span>
					</div>
				</div>
			</div>
        <el-form-item label="商机备注" prop="remark">
          <el-input size="large" type="textarea" resize="none" class="textReset" style="width: 575px;" :rows="5" v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer text-right pr8">
        <el-button class="cancelSubBtn" @click="reset()">重 置</el-button>
		<el-button type="primary" @click="submitForm" class="mainSubBtn">提 交</el-button>
      </div>
    </el-dialog>
    <!--    分配弹出框-->
    <el-dialog :title="title" center v-model="allocationFormOpen" width="385px" append-to-body>
      <el-form ref="refAllocationForm" :model="allocationForm" :rules="allocationFormRules" label-width="80px">
        <el-form-item label="接收部门:" prop="deptId">
          <el-tree-select
		      size="large"
              v-model="allocationForm.departmentId"
              :data="deptOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }"
              value-key="id"
              placeholder="请选择归属部门"
              check-strictly
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer text-right mt30">
		  <el-button class="cancelSubBtn" @click="allocationFormOpen = false">取 消</el-button>
		  <el-button type="primary" @click="allocationSubmit" class="mainSubBtn">确 定</el-button>
      </div>
    </el-dialog>
	<!-- 批量导入商机 -->
	<el-dialog title="商机导入" center v-model="upload.open" width="694px" append-to-body>
	   <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
	      :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
	      :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
			<div>
				<div class="flex col-top">
					<img src="@/assets/images/Img.png" width="80" height="80" alt="" />
					<div class="text-left ml15 mt5" style="text-align: left;">
						<span class="fb color333 mr5 mt5">上传导入商机文件</span>
						<el-link type="primary" :underline="false" 
						style="font-size:12px;vertical-align: baseline;border: 1px solid #4DACB1;background: #EDF6F7;border-radius: 2px;line-height: 22px;padding: 0 4px;"
						   @click.stop="importTemplate">下载模板</el-link>
						<div class="fs12 mt6 mb8">
							 <span>文件后缀名必须为xls 或xlsx（即Excel格式），文件大小不得大于10M，最多支持导入3000条数据</span>
						</div> 
						 <div class="main-color fs12">上传文件</div>
					</div>
				</div>
			</div>
	   </el-upload>
	   <template #footer>
	      <div class="dialog-footer text-right">
			   <el-button class="cancelSubBtn" @click="upload.open = false">取 消</el-button>
			   <el-button type="primary" @click="submitFileForm" class="mainSubBtn">确 定</el-button>
	      </div>
	   </template>
	</el-dialog>
	<!-- 导入结束 -->
    <!--    商机详情-->
    <el-dialog :title="title" center v-model="detailsOpen" width="700px" append-to-body>
      <el-descriptions title="" :column="2" border>
        <el-descriptions-item label="商机来源：">{{ getDictLabel(bus_source, detailsData.opportunitySource) }}
        </el-descriptions-item>
        <el-descriptions-item label="微信号码：">{{ detailsData.wxAccount }}</el-descriptions-item>
        <el-descriptions-item label="客户姓名：">{{ detailsData.customerName }}</el-descriptions-item>
        <el-descriptions-item label="手机号码：">{{ detailsData.phoneNumber }}</el-descriptions-item>
        <el-descriptions-item label="客户地址：">{{ detailsData.customerAddress }}</el-descriptions-item>
        <el-descriptions-item label="客户作物：">{{ detailsData.cropNames }}</el-descriptions-item>
        <el-descriptions-item label="客户需求：">{{ detailsData.customerNeed }}</el-descriptions-item>
        <el-descriptions-item label="添加时间：">{{ detailsData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="客户靶标：">{{ getDictLabel(bus_target, detailsData.customerTarget) }}
        </el-descriptions-item>
        <el-descriptions-item label="归属部门：">{{ detailsData.departName }}</el-descriptions-item>
        <el-descriptions-item label="归属小组：">{{ detailsData.teamName }}</el-descriptions-item>
        <el-descriptions-item label="归属业务经理：">{{ detailsData.businessManagerName }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup name="OpportUnity">
import {
  addOpportunity,
  delOpportunity,
  getOpportunity, getOpportunityInfo, getCropVarietyList,
  listOpportunity, publicAllocation,
  updateOpportunity, deptTreeSelect, getDeptAllListData, getDivisions
} from "@/api/business/opportunity.js";
import {getToken} from "@/utils/auth";

const {proxy} = getCurrentInstance();
const {
  bus_source,
  bus_channel,
  honorific,
  bus_target,
  bus_other_tag,
  bus_customer_allocation
} = proxy.useDict("bus_source", "bus_channel", "honorific", "bus_target", "bus_other_tag", "bus_customer_allocation");

const opportunityList = ref([]);
const open = ref(false);
const allocationFormOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptOptions = ref(undefined);
const cropVarietyList = ref(undefined);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    opportunitySource: null,
    phoneNumber: null,
    distributionStatus: null,
  },
  rules:{
    opportunitySource: [
      { required: true, message: '请选择来源渠道', trigger: 'change' },
    ],
	customerName:[
		{ required: true, message: '请输入客户姓名', trigger: 'blur' },
	],
    phoneNumber:[
  	{ required: true, message: '请输入手机号码', trigger: 'blur' }, 
  	 { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
    ],
    opportunityChannel:[
  	{ required: true, message: '请选择商机渠道', trigger: 'change' },  
    ],
  }
});
const {queryParams, form, rules} = toRefs(data);
//手动分配部门使用
const dataAllocationFormData = reactive({
  allocationForm: {},
  allocationFormParams: {
    ids: 0,
    departmentId: 0,
  },
  allocationFormRules: {
    postName: [{required: true, message: "", trigger: "blur"}],
  }
});
const {allocationFormParams, allocationForm, allocationFormRules} = toRefs(dataAllocationFormData);


/** 查询商机列表 */
function getList() {
  loading.value = true;
  listOpportunity(queryParams.value).then(response => {
    opportunityList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    opportunitySource: null,
    opportunityChannel: null,
    customerName: null,
    customerTitle: null,
    phoneNumber: null,
    wxAccount: null,
    //省编码
    localProvince: null,
    //市编码
    localCity: null,
    //县编码
    localCounty: null,
    //区编码
    localArea: null,
    //省编码
    localProvinceName: null,
    //市编码
    localCityName: null,
    //县编码
    localCountyName: null,
    //区编码
    localAreaName: null,
    //地区名称可以存名称
    customerAddress: null,
    address: null,
    birthday: null,
    cropIds: null,
    customerNeed: null,
    customerTarget: null,
    otherLabels: null,
    remark: null,
    distributionStatus: null,
    distributionType: null,
    deptId: null,
  };
  proxy.resetForm("refForm");
  busTarget()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.opportunityChannel = bus_channel.value[0].value;
  busChannelOnclike(form.value.opportunityChannel)
  open.value = true;
  title.value = "添加商机";
  busTarget()
}
const height1 = ref(false);
const height2 = ref(false);
function busTarget(){
	for(let key in bus_target.value){
		bus_target.value[key].disabled = false
	}
	for(let key in bus_other_tag.value){
		bus_other_tag.value[key].disabled = false
	}
}
const tabItem = (index,num) => {
	// 选中样式
	
	switch (num) {
		case 1:
			// 靶标
			bus_target.value[index].disabled = !bus_target.value[index].disabled
			let arr1 = []
			for (let key in bus_target.value) {
				if(bus_target.value[key].disabled == true){
					arr1.push(bus_target.value[key].value)
				}
			}
			console.log(arr1,'arr1')
			form.value.customerTarget = arr1.length > 0 ? arr1.join(',') : ''
			break;
		case 2:
			// 标签form.otherLabels
			bus_other_tag.value[index].disabled = !bus_other_tag.value[index].disabled
			let arr2 = []
			for (let key in bus_other_tag.value) {
				if(bus_other_tag.value[key].disabled == true){
					arr2.push(bus_other_tag.value[key].value)
				}
			}
			form.value.otherLabels = arr2.length > 0 ? arr2.join(',') : ''
			break;
		}
}			
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value
  getOpportunity(id).then(response => {
    form.value = response.data;
    if (form.value.cropIds != null && form.value.cropIds != '') {
      form.value.cropIds = form.value.cropIds.split(',')
    }
    form.value.address = [form.value.localProvince, form.value.localCity, form.value.localCounty, form.value.localArea]
    open.value = true;
    title.value = "修改商机";
	let customerTarget = form.value.customerTarget ? form.value.customerTarget.split(',') : []
	for (let key in bus_target.value) {
		bus_target.value[key].disabled = false
		for(let j in customerTarget){
			if(customerTarget[j] == bus_target.value[key].value){
				bus_target.value[key].disabled = true
			}
		}		
	}
	
	let otherLabels = form.value.otherLabels ? form.value.otherLabels.split(',') : []
	for (let key in bus_other_tag.value) {
		bus_other_tag.value[key].disabled = false
		for(let j in otherLabels){
			if(otherLabels[j] == bus_other_tag.value[key].value){
				console.log(bus_other_tag.value[key].value,otherLabels[j],'mmm')
				bus_other_tag.value[key].disabled = true
			}
		}		
	}
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["refForm"].validate(valid => {
    if (valid) {
      if (form.value.cropIds != null && Array.isArray(form.value.cropIds)) {
        form.value.cropIds = form.value.cropIds.join(',');
      }
      if (form.value.address != null && Array.isArray(form.value.address)) {
        form.value.localProvince = form.value.address[0];
        form.value.localCity = form.value.address[1];
        form.value.localCounty = form.value.address[2];
        form.value.localArea = form.value.address[3];
        form.value.localProvinceName = labels[0];
        form.value.localCityName = labels[1];
        form.value.localCountyName = labels[2];
        form.value.localAreaName = labels[3];
        form.value.customerAddress = labels[0] + '/' + labels[1] + '/' + labels[2] + '/' + labels[3];
      }
      if (form.value.id != null) {
        updateOpportunity(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOpportunity(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 点击分配 */
function allocationFormSub(row) {
  let id = row.id || ids.value
  allocationFormOpen.value = true;
  title.value = "分配商机";
  if (!Array.isArray(id)) {
    // 如果id不是数组，将其转换为数组，并且只有一个元素
    id = [id];
  }
  allocationForm.value.ids = id.join(',');
}

/** 分配 */
function allocationSubmit() {
  publicAllocation(allocationForm.value).then(response => {
    allocationFormOpen.value = false;
    getList();
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const opIids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除商机编号为"' + opIids + '"的数据项？').then(function () {
    return delOpportunity(opIids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('opportunity/opportunity/export', {
    ...this.queryParams
  }, `opportunity_${new Date().getTime()}.xlsx`)
}

/**
 * 获取部门数据
 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};

/**
 * 获取作物列表
 */
function getCropVariety() {
  getCropVarietyList().then(response => {
    cropVarietyList.value = response.data;
  });
};


/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  // updateSupport: 1,
  // 设置上传的请求头部
  headers: {Authorization: "Bearer " + getToken()},
  // headers: { Authorization: "Bearer " },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/opportunity/importData"
});
/** 下载模板操作 */
function importTemplate() {
   proxy.download("/opportunity/templateDownload", {
   }, `opportunity_template${new Date().getTime()}.xlsx`);
}
/** 导入按钮操作 */
function handleImport() {
  upload.title = "商机导入";
  upload.open = true;
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

/*获取详情*/
const detailsOpen = ref(false);
const detailsData = ref({
  id: null,
  opportunitySource: null,
  wxAccount: null,
  customerName: null,
  phoneNumber: null,
  localArea: null,
  cropNames: null,
  customerNeed: null,
  createTime: null,
  customerTarget: null,
  departName: null,
  teamName: null,
  customerAddress: null,
  businessManagerName: null

});

/** 点击详情按钮 */
function detailsOpenFun(row) {
  const id = row.id || ids.value
  getOpportunityInfo(id).then(response => {
    detailsData.value = response.data;
    detailsOpen.value = true;
    title.value = "商机详情";
  });
};

// 根据字典数据和值获取对应的标签（汉字）
function getDictLabel(dict, value) {
	if(value){
		let arr =  value.split(',')
		let keyString = ''
		for(let j in dict){
			for(let key in arr){
				if(arr[key] == dict[j].value){
					keyString+=dict[j].label+','
				}
			}
		}
		return keyString.slice(0,-1)
	}
};
//获取品牌，事业部数据，线上选择品牌，线下选择事业部
const deptList = ref({
  level: 2,
  channel: 1001
});
const deptListOptions = ref(undefined);

function getDeptList() {
  getDeptAllListData(deptList.value).then(response => {
    deptListOptions.value = response.data;
  });
};

function busChannelOnclike(row) {
  deptList.value.channel = row;
  form.value.deptId = null;
  getDeptList();
}

// 省市区
const address = reactive({
  checkStrictly: false, // 开启懒加载
  lazy: true,
  //可选择任意节点
  lazyLoad: function (node, resolve) { //node为当前点击的节点，resolve为数据加载完成的回调(必须调用)
    setTimeout(() => {
      const nodes = [];
      // 构造查询条件
      let query = {
        id: node.level == 0 ? 0 : node.value,
        level: node.level + 1,
        type: 'provinces',
        pCode: node.value,
        pageNum: 1,
        pageSize: 5000
      }
      if (query.level == 2) {
        query.type = 'cities';
        form.customerAddress = node.label;
      }
      if (query.level == 3) {
        query.type = 'areas';
      }
      if (query.level == 4) {
        query.type = 'streets';
      }
      //查询接口
      getDivisions(query, query.type).then(res => {
        res.rows.map((item) => {
          let obj = {
            value: item.code,
            label: item.name,
            pCode: item.pCode,
            leaf: query.level >= 3
            //leaf: item.hasChildren // 节点级别，如果没有子节点就停止查询
          }
          nodes.push(obj);
        })
        //重新加载节点
        resolve(nodes);
      })
    }, 100);
  }
})
//获取选中的名字
let labels = ref();

function handleChangeAddress(value) {
  if (value == null) {
    form.value.address = null;
    form.value.localProvince = '';
    form.value.localCity = '';
    form.value.localCounty = '';
    form.value.localArea = '';
    form.value.customerAddress = '';
    labels = null;
  } else {
    let nodesObj = proxy.$refs["cascader"].getCheckedNodes();
    labels = nodesObj[0].pathLabels;
  }
}

getDeptList();
getList();
getCropVariety();
getDeptTree();
</script>
<style>
.my-label {
  width: 220px;
  /* height: 40px; */
}

.search_input {
  width: 200px;
  height: 30px;
}
.tagItem{
	height: 38px;
	line-height: 38px;
	color: #333;
	font-size: 14px;
	font-weight: bold;
	width: 73px;
	text-align: right;
}
.cate-item{
	height: 38px;line-height: 38px;
}
.minHeight{
	height: 38px;line-height: 38px;
	overflow: hidden;
}
</style>